package com.codecash.service.impl;

import com.codecash.entity.PageBean;
import com.codecash.entity.Task;
import com.codecash.entity.TaskOrder;
import com.codecash.mapper.TaskMapper;
import com.codecash.mapper.TaskOrderMapper;
import com.codecash.service.TaskService;
import com.codecash.util.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class TaskServiceimpl implements TaskService {
    private static final Logger logger = LoggerFactory.getLogger(TaskServiceimpl.class);

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskOrderMapper taskOrderMapper;

    //发布任务
    @Override
    public void create(Task task) {
        // 补充属性值
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        task.setStatus("可接单"); // 设置默认状态为可接单

        // 从ThreadLocal中获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userIdInteger = (Integer) map.get("id"); // 假设ID是Integer
        Long userId = userIdInteger != null ? userIdInteger.longValue() : null; // 显式将Integer转换为Long
        task.setAuthorId(userId);

        taskMapper.create(task);
    }

    //查询任务
    @Override
    public Task getTaskById(Long id) {

        return taskMapper.getTaskById(id);
    }

    //修改任务
    @Override
    public void update(Task task) throws Exception {
        // 从 ThreadLocal 获取当前用户的 ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long currentUserId = ((Number) map.get("id")).longValue();

        // 获取数据库中任务的创建者 ID
        Task existingTask = taskMapper.getTaskById(task.getId());
        if (existingTask == null) {
            throw new Exception("任务不存在");
        }
        // 检查当前用户是否为任务创建者
        if (!existingTask.getAuthorId().equals(currentUserId)) {
            throw new Exception("您无权修改此任务");
        }
        // 更新任务
        task.setUpdateTime(LocalDateTime.now());
        taskMapper.update(task);
    }

    //删任务
    @Override
    public void delete(Task task) throws Exception {
        // 从 ThreadLocal 获取当前用户的 ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long currentUserId = ((Number) map.get("id")).longValue();

        // 获取数据库中任务的创建者 ID
        Task existingTask = taskMapper.getTaskById(task.getId());
        if (existingTask == null) {
            throw new Exception("任务不存在");
        }
        // 检查当前用户是否为任务创建者
        if (!existingTask.getAuthorId().equals(currentUserId)) {
            throw new Exception("您无权删除此任务");
        }
        // 删除任务
        taskMapper.delete(task.getId());
    }

    @Override
    public PageBean<Task> list(Integer pageNum, Integer pageSize, Integer taskId) {
        //创建PageBean对象
        PageBean<Task> pb = new PageBean<>();
        //开启分页查询pagehelper
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper

        List<Task> as = taskMapper.list(taskId);
        //page中提供了方法，可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<Task> p = (Page<Task>) as;
        //把数据填充到PageBean中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public List<Task> findAllmyTasks(Long currentUserId) {
        return taskMapper.findAllmyTasks(currentUserId);
    }

    @Override
    @Transactional
    public void orderTask(Long taskId, Long userId) throws Exception {
        logger.info("Processing order for task: {} by user: {}", taskId, userId);

        // 1. 检查任务是否存在且可接单
        Task task = taskMapper.getTaskById(taskId);
        if (task == null) {
            logger.error("Task not found: {}", taskId);
            throw new Exception("任务不存在");
        }
        
        logger.info("Current task status: {}", task.getStatus());  // 添加状态日志

        // 2. 检查任务状态
        if (!"可接单".equals(task.getStatus())) {
            logger.error("Task is not available for order. Current status: {}", task.getStatus());
            throw new Exception("该任务已被接单或已完成");
        }

        // 3. 检查是否是自己发布的任务
        if (task.getAuthorId().equals(userId)) {
            logger.error("User {} attempting to order their own task", userId);
            throw new Exception("不能接自己发布的任务");
        }

        try {
            // 4. 创建订单记录
            taskOrderMapper.createOrder(taskId, userId, LocalDateTime.now());
            logger.info("Order record created for task: {} by user: {}", taskId, userId);

            // 5. 更新任务状态
            task.setStatus("进行中");
            taskMapper.updateStatus(taskId, "进行中");
            logger.info("Task status updated to '进行中' for task: {}", taskId);

            logger.info("Successfully ordered task: {} by user: {}", taskId, userId);
        } catch (Exception e) {
            logger.error("Failed to process order", e);
            throw new Exception("接单失败: " + e.getMessage());
        }
    }

    @Override
    public List<TaskOrder> getUserOrders(Long userId) {
        logger.info("Getting orders for user: {}", userId);
        return taskOrderMapper.getUserOrders(userId);
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, Long userId, String status) throws Exception {
        logger.info("Updating order {} status to {} for user {}", orderId, status, userId);
        
        TaskOrder order = taskOrderMapper.getOrderById(orderId);
        if (order == null) {
            throw new Exception("订单不存在");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new Exception("无权操作此订单");
        }
        
        int updated = taskOrderMapper.updateOrderStatus(orderId, userId, status);
        if (updated == 0) {
            throw new Exception("更新订单状态失败");
        }
        
        logger.info("Order status updated successfully");
    }

    @Override
    public TaskOrder getOrderById(Long orderId) throws Exception {
        TaskOrder order = taskOrderMapper.getOrderById(orderId);
        if (order == null) {
            throw new Exception("订单不存在");
        }
        return order;
    }

    @Override
    @Transactional
    public void updateOrderStatusByTaskId(Long taskId, Long userId, String status) throws Exception {
        logger.info("Updating order status for task: {} to {} by user {}", taskId, status, userId);
        
        // 验证状态值
        if (!TaskOrder.STATUS_IN_PROGRESS.equals(status) && 
            !TaskOrder.STATUS_COMPLETED.equals(status) && 
            !TaskOrder.STATUS_CANCELLED.equals(status)) {  // 添加取消状态验证
            logger.error("Invalid status value: {}", status);
            throw new Exception("无效的状态值，只能是'进行中'、'已完成'或'已取消'");
        }
        
        TaskOrder order = taskOrderMapper.getOrderByTaskId(taskId);
        if (order == null) {
            throw new Exception("未找到该任务的订单记录");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new Exception("无权操作此订单");
        }
        
        int updated = taskOrderMapper.updateOrderStatusByTaskId(taskId, userId, status);
        if (updated == 0) {
            throw new Exception("更新订单状态失败");
        }
        
        // 如果订单状态更新成功，同时更新任务状态
        taskMapper.updateStatus(taskId, status);
        
        logger.info("Order status updated successfully for task: {}", taskId);
    }
}